﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Common;
using Model;

namespace AcceptServer.Service
{
    class CommonProtocol
    {
        OperateDataBase operateDataBase = new OperateDataBase();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="realData"></param>
        /// <param name="type">0---Taxi,1---PhoneUser</param>
        public byte[] GetNearbyTaxiInfoData(byte[] realData, int type)
        {
            try
            {
                #region Get ReceData Infomation
                const ushort taxiCount = ConstParameters.MaxTaxiInfoInOneMessage;// Max carinfo in one Command (Must less than 23)
                byte[] tempData = new byte[5];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
                double longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
                double latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                int distance = realData[27];

                byte[] phoneNumberbyts = new byte[6];
                Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
                byte[] serialNumber = new byte[2];
                Array.Copy(realData, 11, serialNumber, 0, 2);
                #endregion
                // get Nearby TaxiIfo
                List<Model.TaxiInfo> taxiInfos = AcceptMainForm.PositionService.GetNearbyGps(longitude, latitude, distance, type);
                ushort cmdCount = Convert.ToUInt16(taxiInfos.Count / taxiCount);
                if (taxiInfos.Count % taxiCount == 0 && cmdCount > 0)
                {
                    cmdCount--;
                }
                int tempTaxiIndex = 0;
                List<byte> messageDatas = new List<byte>();
                Console.WriteLine("一共有" + taxiInfos.Count + "辆出租车。");

                for (ushort i = 0; i <= cmdCount; i++)
                {
                    List<byte> messageBody = new List<byte>();
                    ushort j = 0;
                    if (taxiInfos.Count > 0)
                    {
                        for (; j < taxiCount; j++)
                        {
                            if (tempTaxiIndex < taxiInfos.Count)
                            {
                                #region add TaxiInfo to Data

                                Model.TaxiInfo taxiInfo = taxiInfos[tempTaxiIndex];
                                //longitude 5
                                string longitudestr =
                                    ((taxiInfo.Longitude * Math.Pow(10, 6)).ToString().PadLeft(10, '0'));
                                byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                                messageBody.AddRange(longitudeBytes);
                                //latitude 5
                                string latitudestr =
                                    (taxiInfo.Latitude * Math.Pow(10, 6)).ToString().PadLeft(10, '0');

                                byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                                messageBody.AddRange(latitudeBytes);
                                //ip 4
                                //string[] iplist = taxiInfo.Ip.ToString().Split('.');
                                //messageBody.AddRange(iplist.Select(s => byte.Parse(s, NumberStyles.Integer)));
                                messageBody.AddRange(taxiInfo.Ip.GetAddressBytes());
                                //TaxiState 1
                                messageBody.Add(taxiInfo.TaxiState);
                                //DriverPhoneNumber 6
                                messageBody.AddRange(CommonRoutine.BcdStringToBytes(taxiInfo.DriverPhoneNumber.PadLeft(12, '0')));
                                //TaxiNo 8
                                byte[] taxiNobytes = new byte[8];
                                byte[] tempTaxiNobytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiNo);
                                for (int k = 0; k < taxiNobytes.Length; k++)
                                {
                                    if (k < tempTaxiNobytes.Length)
                                    {
                                        taxiNobytes[k] = tempTaxiNobytes[k];
                                    }
                                    else
                                    {
                                        taxiNobytes[k] = 32;
                                    }
                                }
                                messageBody.AddRange(taxiNobytes);
                                //TaxiType 12
                                byte[] taxiTypebytes = new byte[12];
                                byte[] tempTaxiTypebytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiType);
                                for (int k = 0; k < taxiTypebytes.Length; k++)
                                {
                                    if (k < tempTaxiTypebytes.Length)
                                    {
                                        taxiTypebytes[k] = tempTaxiTypebytes[k];
                                    }
                                    else
                                    {
                                        taxiTypebytes[k] = 32;
                                    }
                                }

                                messageBody.AddRange(taxiTypebytes);
                                #endregion
                                tempTaxiIndex++;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    byte[] taxiCountBytes = BitConverter.GetBytes(j);
                    foreach (var taxiCountByte in taxiCountBytes)
                    {
                        messageBody.Insert(0, taxiCountByte);
                    }
                    bool isSubPackage;
                    ushort packgeCounts;
                    ushort packageIndex;
                    if (taxiInfos.Count == 0 || cmdCount == 0)
                    {
                        isSubPackage = false;
                        packgeCounts = 1;
                        packageIndex = 1;
                    }
                    else
                    {
                        isSubPackage = true;
                        packgeCounts = (ushort)(cmdCount + 1);
                        packageIndex = (ushort)(i + 1);
                    }
                    ushort messageid;
                    if (type == ConstParameters.TypePhoneUser)
                    {
                        messageid = ConstParameters.CmdPhoneUserGetNearbyTaxiReply;
                    }
                    else
                    {
                        messageid = ConstParameters.CmdTaxiGetNearbyTaxiReply;
                    }

                    byte[] messageHead = OperateAgreement.GetMessageHead(messageid, isSubPackage,
                                                        false, messageBody.Count, phoneNumberbyts, serialNumber,
                                                    packgeCounts, packageIndex);

                    //List<byte> messageData = new List<byte> { 0x7e };
                    //messageData.AddRange(messageHead);
                    //messageData.AddRange(messageBody);
                    //messageData.Add(0x00); //temp;
                    //messageData.Add(0x7e);
                    //byte[] messageDatabytes = messageData.ToArray();
                    //messageDatabytes[messageDatabytes.Length - 2] = CommonRoutine.GetCheckBit(messageDatabytes);
                    messageDatas.AddRange(OperateAgreement.PackageSendData(messageHead, messageBody.ToArray()));
 
                }

                return messageDatas.ToArray();
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("CommonProtocol.cs-168");
                return null;
            }

        }

         
        public byte[] GetNearbyTaxiInfoDataByCarType(byte[] realData, 
            int usertype)
        {
            try
            {
                string phoneNumbertemp = Common.OperateAgreement.GetPhoneNumInMessageHead(realData);
                #region Get ReceData Infomation
                const ushort taxiCount = ConstParameters.MaxTaxiInfoInOneMessage;// Max carinfo in one Command (Must less than 23)
                byte[] tempData = new byte[5];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
                double longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
                double latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                int distance = realData[27];
                byte carType = realData[28];//*******
   
                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine(longitude);
                    Console.WriteLine(latitude);
                }
                byte[] phoneNumberbyts = new byte[6];
                Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
                byte[] serialNumber = new byte[2];
                Array.Copy(realData, 11, serialNumber, 0, 2);
                #endregion
                //***************
                List<Model.TaxiInfo> taxiInfos = 
                    AcceptMainForm.PositionService.GetNearbyGpsByCarType(
                    phoneNumbertemp,longitude, latitude, distance, usertype,carType);
                ushort cmdCount = Convert.ToUInt16(taxiInfos.Count / taxiCount);
                if (taxiInfos.Count % taxiCount == 0 && cmdCount > 0)
                {
                    cmdCount--;
                }
                int tempTaxiIndex = 0;
                List<byte> messageDatas = new List<byte>();
                if(phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine("一共有" + taxiInfos.Count + "辆出租车。");
                }
              

                for (ushort i = 0; i <= cmdCount; i++)
                {
                    List<byte> messageBody = new List<byte>();
                    ushort j = 0;
                    if (taxiInfos.Count > 0)
                    {
                        for (; j < taxiCount; j++)
                        {
                            if (tempTaxiIndex < taxiInfos.Count)
                            {
                                #region add TaxiInfo to Data

                                Model.TaxiInfo taxiInfo = taxiInfos[tempTaxiIndex];
                                //longitude 5
                                string longitudestr =
                                    ((taxiInfo.Longitude * Math.Pow(10, 6)).ToString().PadLeft(10, '0'));
                                byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                                messageBody.AddRange(longitudeBytes);
                                //latitude 5
                                string latitudestr =
                                    (taxiInfo.Latitude * Math.Pow(10, 6)).ToString().PadLeft(10, '0');

                                byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                                messageBody.AddRange(latitudeBytes);
                                //ip 4
                                //string[] iplist = taxiInfo.Ip.ToString().Split('.');
                                //messageBody.AddRange(iplist.Select(s => byte.Parse(s, NumberStyles.Integer)));
                                messageBody.AddRange(taxiInfo.Ip.GetAddressBytes());
                                //TaxiState 1
                                messageBody.Add(taxiInfo.TaxiState);
                                //DriverPhoneNumber 6
                                messageBody.AddRange(CommonRoutine.BcdStringToBytes(taxiInfo.DriverPhoneNumber.PadLeft(12, '0')));
                                //TaxiNo 8
                                byte[] taxiNobytes = new byte[8];
                                if (!string.IsNullOrEmpty(taxiInfo.TaxiNo))
                                {
                                    byte[] tempTaxiNobytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiNo);
                                    for (int k = 0; k < taxiNobytes.Length; k++)
                                    {
                                        if (k < tempTaxiNobytes.Length)
                                        {
                                            taxiNobytes[k] = tempTaxiNobytes[k];
                                        }
                                        else
                                        {
                                            taxiNobytes[k] = 32;
                                        }
                                    }
                                }                             
                                messageBody.AddRange(taxiNobytes);
                                //TaxiType 12
                                byte[] taxiTypebytes = new byte[12];
                                if (!string.IsNullOrEmpty(taxiInfo.TaxiType))
                                {
                                    byte[] tempTaxiTypebytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiType);
                                    for (int k = 0; k < taxiTypebytes.Length; k++)
                                    {
                                        if (k < tempTaxiTypebytes.Length)
                                        {
                                            taxiTypebytes[k] = tempTaxiTypebytes[k];
                                        }
                                        else
                                        {
                                            taxiTypebytes[k] = 32;
                                        }
                                    }
                                
                                }

                                messageBody.AddRange(taxiTypebytes);

                                byte[] angle = BitConverter.GetBytes(taxiInfo.Angle);                                
                                messageBody.Add((byte)taxiInfo.StartLevel);
                                //messageBody.Add(0x04);
                                messageBody.AddRange(angle);
                                messageBody.Add(taxiInfo.Speed);
                                //signature -40bytes
                                byte[] signature = new byte[40];
                                if (!string.IsNullOrEmpty(taxiInfo.Signature))
                                {
                                    byte[] carSignature = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.Signature);
                                    Array.Copy(carSignature, 0, signature, 0, carSignature.Length);
                                }                               
                                messageBody.AddRange(signature);
                                #endregion
                                tempTaxiIndex++;

                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    byte[] taxiCountBytes = BitConverter.GetBytes(j);
                    foreach (var taxiCountByte in taxiCountBytes)
                    {
                        messageBody.Insert(0, taxiCountByte);
                    }
                    bool isSubPackage;
                    ushort packgeCounts;
                    ushort packageIndex;
                    if (taxiInfos.Count == 0 || cmdCount == 0)
                    {
                        isSubPackage = false;
                        packgeCounts = 1;
                        packageIndex = 1;
                    }
                    else
                    {
                        isSubPackage = true;
                        packgeCounts = (ushort)(cmdCount + 1);
                        packageIndex = (ushort)(i + 1);
                    }
                    ushort messageid;
                    if (usertype == ConstParameters.TypePhoneUser)
                    {
                        messageid = ConstParameters.CmdPhoneUserGetNearByByCarTypeReply;
                    }
                    else
                    {
                        messageid = ConstParameters.CmdTaxiGetNearByByCarTypeReply;
                    }

                    messageBody.Insert(0, carType);
                    byte[] messageHead = OperateAgreement.GetMessageHead(messageid, isSubPackage,
                                                        false, messageBody.Count, phoneNumberbyts, serialNumber,
                                                    packgeCounts, packageIndex);
                
                    byte[] sendDataTmp = OperateAgreement.PackageSendData(messageHead, messageBody.ToArray());
                    //Socket s = AcceptMainForm.JudgeIsUnicomNumber(phoneNumbertemp);

                    IPEndPoint ipEndPoint = AcceptMainForm.IpEndPointList[phoneNumbertemp] as IPEndPoint;
                    //s.SendTo(sendDataTmp, sendDataTmp.Length, SocketFlags.None, ipEndPoint);


                    AcceptMainForm.SendDataToIPAddress(sendDataTmp, ipEndPoint, phoneNumbertemp);
                }

                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine(messageDatas.ToArray().Length);
                }

                return  new byte[1];
               // return messageDatas.ToArray();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("CommonProtocol.cs- GetNearbyTaxiInfoDataByCarType");
                return null;
            }

        }
         

        public byte[] GetNearbyCarInfoWithStateByCarType(byte[] realData,
         int usertype)
        {
            try
            {
                string phoneNumbertemp = Common.OperateAgreement.GetPhoneNumInMessageHead(realData);
                #region Get ReceData Infomation
                const ushort taxiCount = ConstParameters.MaxTaxiInfoInOneMessage;// Max carinfo in one Command (Must less than 23)
                byte[] tempData = new byte[5];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
                double longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
                double latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                int distance = realData[27];
                byte carType = realData[28];//*******

                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine(longitude);
                    Console.WriteLine(latitude);
                }
                byte[] phoneNumberbyts = new byte[6];
                Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
                byte[] serialNumber = new byte[2];
                Array.Copy(realData, 11, serialNumber, 0, 2);
                #endregion
                //***************
                List<Model.TaxiInfo> taxiInfos = AcceptMainForm.PositionService.GetNearbyGpsWithStateByCarType(phoneNumbertemp,
                    longitude, latitude, distance, usertype, carType);
                ushort cmdCount = Convert.ToUInt16(taxiInfos.Count / taxiCount);
                if (taxiInfos.Count % taxiCount == 0 && cmdCount > 0)
                {
                    cmdCount--;
                }
                int tempTaxiIndex = 0;
                List<byte> messageDatas = new List<byte>();
                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine("一共有" + taxiInfos.Count + "辆出租车。");
                }


                for (ushort i = 0; i <= cmdCount; i++)
                {
                    List<byte> messageBody = new List<byte>();
                    ushort j = 0;
                    if (taxiInfos.Count > 0)
                    {
                        for (; j < taxiCount; j++)
                        {
                            if (tempTaxiIndex < taxiInfos.Count)
                            {
                                #region add TaxiInfo to Data

                                Model.TaxiInfo taxiInfo = taxiInfos[tempTaxiIndex];
                                //longitude 5
                                string longitudestr =(taxiInfo.Longitude * Math.Pow(10, 6)).ToString();
                                
                                if (longitudestr.Contains('.'))
                                {
                                    longitudestr = longitudestr.Remove(longitudestr.IndexOf('.'));                                   
                                }
                                longitudestr = longitudestr.PadLeft(10, '0');
                                byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                                messageBody.AddRange(longitudeBytes);
                                //latitude 5
                                string latitudestr =(taxiInfo.Latitude * Math.Pow(10, 6)).ToString();
                                if (latitudestr.Contains('.'))
                                {
                                    latitudestr = latitudestr.Remove(latitudestr.IndexOf('.')); 
                                }
                                latitudestr = latitudestr.PadLeft(10, '0');

                                byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                                messageBody.AddRange(latitudeBytes);
                                //ip 4
                                //string[] iplist = taxiInfo.Ip.ToString().Split('.');
                                //messageBody.AddRange(iplist.Select(s => byte.Parse(s, NumberStyles.Integer)));
                                messageBody.AddRange(taxiInfo.Ip.GetAddressBytes());
                                //TaxiState 1
                                messageBody.Add(taxiInfo.TaxiState);
                                //DriverPhoneNumber 6
                                messageBody.AddRange(CommonRoutine.BcdStringToBytes(taxiInfo.DriverPhoneNumber.PadLeft(12, '0')));
                                //TaxiNo 8
                                byte[] taxiNobytes = new byte[8];
                                if (!string.IsNullOrEmpty(taxiInfo.TaxiNo))
                                {
                                    byte[] tempTaxiNobytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiNo);
                                    for (int k = 0; k < taxiNobytes.Length; k++)
                                    {
                                        if (k < tempTaxiNobytes.Length)
                                        {
                                            taxiNobytes[k] = tempTaxiNobytes[k];
                                        }
                                        else
                                        {
                                            taxiNobytes[k] = 32;
                                        }
                                    }
                                }
                                messageBody.AddRange(taxiNobytes);
                                //TaxiType 12
                                byte[] taxiTypebytes = new byte[12];
                                if (!string.IsNullOrEmpty(taxiInfo.TaxiType))
                                {
                                    byte[] tempTaxiTypebytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiType);
                                    for (int k = 0; k < taxiTypebytes.Length; k++)
                                    {
                                        if (k < tempTaxiTypebytes.Length)
                                        {
                                            taxiTypebytes[k] = tempTaxiTypebytes[k];
                                        }
                                        else
                                        {
                                            taxiTypebytes[k] = 32;
                                        }
                                    }

                                }

                                messageBody.AddRange(taxiTypebytes);

                                byte[] angle = BitConverter.GetBytes(taxiInfo.Angle);
                                messageBody.Add((byte)taxiInfo.StartLevel);
                                //messageBody.Add(0x04);
                                messageBody.AddRange(angle);
                                messageBody.Add(taxiInfo.Speed);
                                //signature -40bytes
                                byte[] signature = new byte[40];
                                if (!string.IsNullOrEmpty(taxiInfo.Signature))
                                {
                                    byte[] carSignature = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.Signature);
                                    Array.Copy(carSignature, 0, signature, 0, carSignature.Length);
                                }
                                messageBody.AddRange(signature);
                               
                                #endregion
                                tempTaxiIndex++;

                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    byte[] taxiCountBytes = BitConverter.GetBytes(j);
                    foreach (var taxiCountByte in taxiCountBytes)
                    {
                        messageBody.Insert(0, taxiCountByte);
                    }
                    bool isSubPackage;
                    ushort packgeCounts;
                    ushort packageIndex;
                    if (taxiInfos.Count == 0 || cmdCount == 0)
                    {
                        isSubPackage = false;
                        packgeCounts = 1;
                        packageIndex = 1;
                    }
                    else
                    {
                        isSubPackage = true;
                        packgeCounts = (ushort)(cmdCount + 1);
                        packageIndex = (ushort)(i + 1);
                    }
                    ushort messageid;
                    if (usertype == ConstParameters.TypePhoneUser)
                    {
                        messageid = ConstParameters.CmdPhoneUserGetNearbyCarReply;
                    }
                    else
                    {
                        //************此处为出租车用户搜索 暂时未使用***********
                        messageid = ConstParameters.CmdTaxiGetNearByByCarTypeReply;
                    }

                    messageBody.Insert(0, carType);
                    byte[] messageHead = OperateAgreement.GetMessageHead(messageid, isSubPackage,
                                                        false, messageBody.Count, phoneNumberbyts, serialNumber,
                                                    packgeCounts, packageIndex);

                    byte[] sendDataTmp = OperateAgreement.PackageSendData(messageHead, messageBody.ToArray());
                    //Socket s = AcceptMainForm.JudgeIsUnicomNumber(phoneNumbertemp);

                    IPEndPoint ipEndPoint = AcceptMainForm.IpEndPointList[phoneNumbertemp] as IPEndPoint;
                    //s.SendTo(sendDataTmp, sendDataTmp.Length, SocketFlags.None, ipEndPoint);


                    AcceptMainForm.SendDataToIPAddress(sendDataTmp, ipEndPoint, phoneNumbertemp);
                }

                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine(messageDatas.ToArray().Length);
                }

                return new byte[1];
                // return messageDatas.ToArray();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("CommonProtocol.cs- GetNearbyTaxiInfoDataByCarType");
                return null;
            }

        }

         
        /// <summary>
        /// Add 3 byte
        /// </summary>
        /// <param name="realData"></param>
        /// <param name="type">0---Taxi,1---PhoneUser</param>
        public byte[] GetNearbyTaxiInfoData2(byte[] realData, int type)
        {
            try
            {
                string phoneNumbertemp = Common.OperateAgreement.GetPhoneNumInMessageHead(realData);
                #region Get ReceData Infomation
                const ushort taxiCount = ConstParameters.MaxTaxiInfoInOneMessage;// Max carinfo in one Command (Must less than 23)
                byte[] tempData = new byte[5];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
                double longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
                double latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                int distance = realData[27];

                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine(longitude);
                    Console.WriteLine(latitude);
                }
                byte[] phoneNumberbyts = new byte[6];
                Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
                byte[] serialNumber = new byte[2];
                Array.Copy(realData, 11, serialNumber, 0, 2);
                #endregion
                // get Nearby TaxiIfo
                List<Model.TaxiInfo> taxiInfos = AcceptMainForm.PositionService.GetNearbyGps(longitude, latitude, distance, type);
                ushort cmdCount = Convert.ToUInt16(taxiInfos.Count / taxiCount);
                if (taxiInfos.Count % taxiCount == 0 && cmdCount > 0)
                {
                    cmdCount--;
                }
                int tempTaxiIndex = 0;
                List<byte> messageDatas = new List<byte>();
                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine("一共有" + taxiInfos.Count + "辆出租车。");
                }


                for (ushort i = 0; i <= cmdCount; i++)
                {
                    List<byte> messageBody = new List<byte>();
                    ushort j = 0;
                    if (taxiInfos.Count > 0)
                    {
                        for (; j < taxiCount; j++)
                        {
                            if (tempTaxiIndex < taxiInfos.Count)
                            {
                                #region add TaxiInfo to Data

                                Model.TaxiInfo taxiInfo = taxiInfos[tempTaxiIndex];
                                //longitude 5
                                string longitudestr =
                                    ((taxiInfo.Longitude * Math.Pow(10, 6)).ToString().PadLeft(10, '0'));
                                byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                                messageBody.AddRange(longitudeBytes);
                                //latitude 5
                                string latitudestr =
                                    (taxiInfo.Latitude * Math.Pow(10, 6)).ToString().PadLeft(10, '0');

                                byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                                messageBody.AddRange(latitudeBytes);
                                //ip 4
                                //string[] iplist = taxiInfo.Ip.ToString().Split('.');
                                //messageBody.AddRange(iplist.Select(s => byte.Parse(s, NumberStyles.Integer)));
                                messageBody.AddRange(taxiInfo.Ip.GetAddressBytes());
                                //TaxiState 1
                                messageBody.Add(taxiInfo.TaxiState);
                                //DriverPhoneNumber 6
                                messageBody.AddRange(CommonRoutine.BcdStringToBytes(taxiInfo.DriverPhoneNumber.PadLeft(12, '0')));
                                //TaxiNo 8
                                byte[] taxiNobytes = new byte[8];
                                byte[] tempTaxiNobytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiNo);
                                for (int k = 0; k < taxiNobytes.Length; k++)
                                {
                                    if (k < tempTaxiNobytes.Length)
                                    {
                                        taxiNobytes[k] = tempTaxiNobytes[k];
                                    }
                                    else
                                    {
                                        taxiNobytes[k] = 32;
                                    }
                                }
                                messageBody.AddRange(taxiNobytes);
                                //TaxiType 12
                                byte[] taxiTypebytes = new byte[12];
                                byte[] tempTaxiTypebytes = Encoding.GetEncoding("GBK").GetBytes(taxiInfo.TaxiType);
                                for (int k = 0; k < taxiTypebytes.Length; k++)
                                {
                                    if (k < tempTaxiTypebytes.Length)
                                    {
                                        taxiTypebytes[k] = tempTaxiTypebytes[k];
                                    }
                                    else
                                    {
                                        taxiTypebytes[k] = 32;
                                    }
                                }

                                messageBody.AddRange(taxiTypebytes);

                                byte[] angle = BitConverter.GetBytes(taxiInfo.Angle);
                                messageBody.Add(0X04);
                                //messageBody.Add((byte)taxiInfo.StartLevel);
                                messageBody.AddRange(angle);
                                messageBody.Add(taxiInfo.Speed);
                                #endregion
                                tempTaxiIndex++;

                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    byte[] taxiCountBytes = BitConverter.GetBytes(j);
                    foreach (var taxiCountByte in taxiCountBytes)
                    {
                        messageBody.Insert(0, taxiCountByte);
                    }
                    bool isSubPackage;
                    ushort packgeCounts;
                    ushort packageIndex;
                    if (taxiInfos.Count == 0 || cmdCount == 0)
                    {
                        isSubPackage = false;
                        packgeCounts = 1;
                        packageIndex = 1;
                    }
                    else
                    {
                        isSubPackage = true;
                        packgeCounts = (ushort)(cmdCount + 1);
                        packageIndex = (ushort)(i + 1);
                    }
                    ushort messageid;
                    if (type == ConstParameters.TypePhoneUser)
                    {
                        messageid = ConstParameters.CmdPhoneUserGetNearbyTaxiReply2;
                    }
                    else
                    {
                        messageid = ConstParameters.CmdTaxiGetNearbyTaxiReply2;
                    }

                    byte[] messageHead = OperateAgreement.GetMessageHead(messageid, isSubPackage,
                                                        false, messageBody.Count, phoneNumberbyts, serialNumber,
                                                    packgeCounts, packageIndex);

                    //List<byte> messageData = new List<byte> { 0x7e };
                    //messageData.AddRange(messageHead);
                    //messageData.AddRange(messageBody);
                    //messageData.Add(0x00); //temp;
                    //messageData.Add(0x7e);
                    //byte[] messageDatabytes = messageData.ToArray();
                    //messageDatabytes[messageDatabytes.Length - 2] = CommonRoutine.GetCheckBit(messageDatabytes);
                    // messageDatas.AddRange(OperateAgreement.PackageSendData(messageHead, messageBody.ToArray()));
                    byte[] sendDataTmp = OperateAgreement.PackageSendData(messageHead, messageBody.ToArray());
                   // Socket s = AcceptMainForm.JudgeIsUnicomNumber(phoneNumbertemp);

                    IPEndPoint ipEndPoint = AcceptMainForm.IpEndPointList[phoneNumbertemp] as IPEndPoint;
                    //s.SendTo(sendDataTmp, sendDataTmp.Length, SocketFlags.None, ipEndPoint);
                    AcceptMainForm.SendDataToIPAddress(sendDataTmp, ipEndPoint, phoneNumbertemp);
                }

                if (phoneNumbertemp == "18602789588")
                {
                    Console.WriteLine(messageDatas.ToArray().Length);
                }

                return new byte[1];
                // return messageDatas.ToArray();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("CommonProtocol.cs-337");
                return null;
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="realData"></param>
        /// <param name="type">0---Taxi,1---PhoneUser</param>
        public byte[] UploadingTradeinfo(byte[] realData, int type)
        {
            try
            {
            TradeInfo tradeInfo = new TradeInfo();

            //phoneNumber in message head
            tradeInfo.PhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

            byte[] tradeTimebytes = new byte[7];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, tradeTimebytes, 0, 7);
            string tradeTimestr = CommonRoutine.ByteToBcdString(tradeTimebytes);
            tradeInfo.TradeTime = DateTime.ParseExact(tradeTimestr, "yyyyMMddHHmmss", null);

            byte[] phoneNumberbyts2 = new byte[6];
            Array.Copy(realData, 24, phoneNumberbyts2, 0, 6);
            tradeInfo.PhoneNumber2 = CommonRoutine.ByteToBcdString(phoneNumberbyts2).Remove(0, 1);
            tradeInfo.Type = type;

                operateDataBase.AddTradeInfo(tradeInfo);
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("CommonProtocol.cs-371");
            }

            byte[] tempBytes =new byte[1];
               
            if (type == ConstParameters.TypePhoneUser)
            {
                tempBytes= OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdPhoneUserUploadingTradeinfoReply);
            }
            else if (type == ConstParameters.TypeTaxi)
            {
                tempBytes = OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdTaxiUploadingTradeinfoReply);
            }
            return tempBytes;

        }




    }
}
